package com.uziot.bucket.transactional.cases;

import com.uziot.bucket.transactional.dao.domain.SysUser;
import com.uziot.bucket.transactional.dao.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author shidt
 * @version V1.0
 * @className Case03
 * @date 2021-05-15 22:37:58
 * @description
 */

@Slf4j
@Component
public class Case08 {

    @Autowired
    private SysUserMapper sysUserMapper;


    /**
     * 非运行异常，且没有通过 rollbackFor 指定抛出的异常，不生效
     * spring事务默认异常回滚为运行时异常
     * 上面这种场景不生效很好理解，子线程的异常不会被外部的线程捕获，
     * 这个方法的调用不抛异常，因此不会触发事务回滚
     */
    @Transactional(rollbackFor = IllegalArgumentException.class)
    public boolean testCompileException(long id) {
        new Thread(() -> {
            log.info("开始子线程更新");
            SysUser sysUser = sysUserMapper.selectByPrimaryKey(id);
            sysUser.setNickName("测试昵称06");
            sysUserMapper.updateByPrimaryKeySelective(sysUser);

            sysUser.setDeptId(1006L);

            // 抛出异常和捕获的异常不一致导致事务无法回退
            sysUserMapper.updateByPrimaryKeySelective(sysUser);
            throw new IllegalArgumentException("异常抛出未拦截回滚");
        }).start();

        return false;
    }

}
